package com.ikingtech.platform.service.office.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.office.model.dto.OfficeDataCustomManagementDto;
import com.ikingtech.framework.sdk.office.model.enums.OfficeDataEnums;
import com.ikingtech.framework.sdk.office.model.query.OfficeDataManagementQuery;
import com.ikingtech.framework.sdk.office.model.vo.OfficeDataCustomManagementVo;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.office.entity.OfficeDataCustomFields;
import com.ikingtech.platform.service.office.entity.OfficeDataCustomManagement;
import com.ikingtech.platform.service.office.mapper.OfficeDataCustomManagementMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * office-自定义数据管理 服务实现类
 * </p>
 *
 * @author lqb
 */
@Slf4j
@RequiredArgsConstructor
public class OfficeDataCustomManagementService extends ServiceImpl<OfficeDataCustomManagementMapper, OfficeDataCustomManagement> {

    private final OfficeDataCustomFieldsService officeDataCustomFieldsService;

    /**
     * 新增
     *
     * @param dto 提交参数
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> add(OfficeDataCustomManagementDto dto) {
        OfficeDataCustomManagement management = dto.copy(new OfficeDataCustomManagement());
        management.setResultType(OfficeDataEnums.ResultType.OBJECT)
                .setSortOrder(this.baseMapper.getMaxSortOrder(dto.getBusinessType()) + 1)
                .setId(Tools.Id.uuid());
        management.insert();
        return R.ok();
    }

    /**
     * 编辑
     *
     * @param dto 提交参数
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> update(OfficeDataCustomManagementDto dto) {
        dto.copy(new OfficeDataCustomManagement())
                .updateById();
        return R.ok();
    }

    /**
     * 列表查询
     *
     * @return 执行结果
     */
    public R<List<OfficeDataCustomManagementVo>> queryList(OfficeDataManagementQuery query) {
        List<OfficeDataCustomManagementVo> list = this.baseMapper.queryList(query);
        return R.ok(list);
    }

    /**
     * 删去
     *
     * @param id id
     * @return 执行结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R<String> delete(String id) {
        this.removeById(id);
        List<OfficeDataCustomFields> fieldsList = this.officeDataCustomFieldsService.lambdaQuery()
                .eq(OfficeDataCustomFields::getOfficeDataCustomManagementId, id).list();
        fieldsList.forEach(fields -> this.officeDataCustomFieldsService.delete(fields.getId()));
        return R.ok();
    }
}

